package com.yinzifan.manager.controller;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.yinzifan.entity.Product;
import com.yinzifan.manager.service.ProductService;

import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/products")
public class ProductController {

	private static final Logger LOGGER = LoggerFactory.getLogger(ProductController.class);

	@Autowired
	private ProductService productService;

	@ApiOperation(value="创建产品", notes = "根据对应的业务规则添加相应的产品")
	@PostMapping
	public Product addProduct(@RequestBody Product product) {
		LOGGER.debug("请求参数: {}", product);

		Product result = productService.addProduct(product);

		LOGGER.debug("保存结果: {}", result);
		return result;
	}

	@GetMapping(value = "/{id}")
	public Product findOne(@PathVariable String id) {
		Product result = productService.findOne(id);
		return result;
	}

	@GetMapping
	public Page<Product> query(String ids, BigDecimal minRewardRate, BigDecimal maxRewardRate, String status,
			@RequestParam(defaultValue = "0") int pageNum, @RequestParam(defaultValue = "10") int pageSize) {
		LOGGER.info("查询产品,ids={},minRewardRate={},maxRewardRate={},status,pageNum={},pageSize={}");
		List<String> idList = null, statusList = null;
		if (!StringUtils.isEmpty(ids)) {
			idList = Arrays.asList(ids.split(","));
		}
		if (!StringUtils.isEmpty(status)) {
			statusList = Arrays.asList(status.split(","));
		}

		PageRequest pageable = PageRequest.of(pageNum, pageSize);
		Page<Product> page = productService.query(idList, minRewardRate, maxRewardRate, statusList, pageable);
		LOGGER.info("查询产品,结果={}", page);
		return page;
	}

}
